<?php

namespace app\common\service;

use app\common\service\Base;
use think\Db;

class Material extends Base
{

	// 裁床面料需要检测的关键词
	public $filterFabricKeyArr = [];

	// 裁床后辅料需要检测的关键词（朴、透明条、织带、橡筋）
	public $filterAccessoriesKeyArr = ['朴', '透明条', '织带', '橡筋'];

	/**
	 * 根据ID获取材料
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param integer $id
	 * @return array
	 */
	public function getInfoById($id, $field='*') {
		if (empty($id)) return [];
		return db('material')->where('id', $id)->field($field)->findOrEmpty();
	}

	/**
	 * 根据SKU获取材料
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param string $sku
	 * @return array
	 */
	public function getInfoBySku($sku, $field='*') {
		if (empty($sku)) return [];
		return db('material')->where('material_sku', $sku)->field($field)->findOrEmpty();
	}

	/**
	 * 获取物料名称
	 *
	 * @author KING
	 * @date 2020年7月29日
	 *
	 * @param integer $id
	 */
	public function getMaterialName($id) {
		$name = cache(MATERIAL_NAME . $id);
		if ($name != '') return $name;
		$info = $this->getInfoById($id, 'name');
		if (empty($info)) return '';
		cache(MATERIAL_NAME . $id, $info['name'], 8640000);
		return $info['name'];
	}

	/**
	 * 检测物料是否包含指定关键词
	 *
	 * @author King
	 * @date 2020年8月27日
	 *
	 * @param string $materialName
	 * @param string $type		物料类型（面fabric,辅accessories）
	 * @return boolean
	 */
	public function checkIsIncludeKeys($materialName, $type='fabric') {
		$arr = $type=='fabric' ? $this->filterFabricKeyArr : $this->filterAccessoriesKeyArr;
		foreach ($arr as $key) {
			if (mb_strpos($materialName, $key) !== false) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 检测物料SKU是否存在
	 *
	 * @author KING
	 * @date 2020年7月10日
	 *
	 * @param string $materialSku
	 * @param number $exceptId		排除的主键ID
	 * @return boolean
	 */
	public function checkSkuExist($materialSku, $exceptId=0) {
		$where = [];
		$where[] = ['material_sku', '=', $materialSku];
		if ($exceptId) $where[] = ['id', '!=', $exceptId];
		$info = db('material')->where($where)->field('id')->findOrEmpty();
		return $info?true:false;
	}

	/**
	 * 检测物料名称是否存在
	 *
	 * @author KING
	 * @date 2020年7月10日
	 *
	 * @param string $name
	 * @param number $exceptId		排除的主键ID
	 * @return boolean
	 */
	public function checkNameExist($name, $exceptId=0) {
		$where = [];
		$where[] = ['name', '=', $name];
		if ($exceptId) $where[] = ['id', '<>', $exceptId];
		$info = db('material')->where($where)->field('id')->findOrEmpty();
		return $info?true:false;
	}
	/**
	 * 工厂订单统计
	 *
	 * @date 2021年3月10日
	 *
	 */
	public function getFactoryOrderStat($where=[]){
        $factoryKV = getFactoryKV(false);
        $tbPre = config('database.prefix');

        $listA = Db::table($tbPre . 'order_size')->where('order_id', 'IN', function ($query) use($tbPre, $where) {
        	$query->table($tbPre . 'order')->where($where)->field('id');
        })->group('factory_id')->column('sum(order_count) as order_count,sum(shicai_count) as shicai_count,sum(jiaohuo_count) as jiaohuo_count,sum(daohuo_count) as daohuo_count','factory_id');

        $listB = Db::table($tbPre . 'order_material')->where('order_id', 'IN', function ($query) use($tbPre, $where) {
        	$query->table($tbPre . 'order')->where($where)->field('id');
        })->group('factory_id')->column('sum(fabric_price_amount) as fabric_price_amount,sum(dosage_price_amount) as dosage_price_amount,sum(customer_dosage*customer_price*(1+loss/100)*shicai_count-caigou_subtotal_money+fabric_price_amount+dosage_price_amount) as profit_loss','factory_id');

        $listC = Db::table($tbPre . 'material_stock')->where('order_id', 'IN', function ($query) use($tbPre, $where) {
        	$query->table($tbPre . 'order')->where($where)->field('id');
        })->group('factory_id')->column('sum(metre_left) as metre_left,sum(unit_price_metre*metre_left) as metre_money','factory_id');

        $result = [];
        foreach ($listA as $factoryId => $v) {
        	$result[] = [
        		'order_count'=>arrayGet($v, 'order_count', 0),
        		'shicai_count'=>arrayGet($v, 'shicai_count', 0),
        		'jiaohuo_count'=>arrayGet($v, 'jiaohuo_count', 0),
        		'daohuo_count'=>arrayGet($v, 'daohuo_count', 0),
        		'profit_loss'=>round(arrayGet(arrayGet($listB, $factoryId, []), 'profit_loss', 0)),
        		'metre'=>round(arrayGet(arrayGet($listC, $factoryId, []), 'fabric_price_amount', 0)),
        		'metre_money'=>round(arrayGet(arrayGet($listC, $factoryId, []), 'metre_left', 0)),
        		'fabric_price_amount'=>round(arrayGet(arrayGet($listB, $factoryId, []), 'metre_money', 0)),
        		'dosage_price_amount'=>round(arrayGet(arrayGet($listB, $factoryId, []), 'dosage_price_amount', 0)),
        		'factory_id'=>$factoryId,
        		'factory'=>arrayGet($factoryKV, $factoryId,'未分组'),
        	];
        }
		return $result;
	}

    //返回材料类型
    public function formatMaterialType($str, $defaultVal='其它', $model=2) {
        if ($model==1) {
            if ($str == 'fabric') return "<span style='color:#009688'>面料</span>";
            else if ($str == 'lining') return "<span style='color:#5FB878'>里料</span>";
            else if ($str == 'accessories') return "<span style='color:#1E9FFF'>辅料</span>";
            else return $defaultVal;
        } else if ($model==2) {
            if ($str == 'fabric') return '<span class="layui-badge layui-bg-green">面</span> ';
            else if ($str == 'lining') return '<span class="layui-badge layui-bg-cyan">里</span> ';
            else if ($str == 'accessories') return '<span class="layui-badge layui-bg-blue">辅</span> ';
            else return $defaultVal;
        }
    }
}